# -*- coding:utf-8 -*-

import datetime

from . import api
from iHome import db
from iHome.models import Order, House
from iHome.utils.response_code import RET
from iHome.utils.commons import login_required
from flask import g, request, jsonify, current_app


@api.route("/orders", methods=["POST"])
@login_required
def add_order():
    """添加订单"""
    # 1. 获取参数
    user_id = g.user_id
    data_json = request.json
    house_id = data_json.get("house_id")
    start_data_str = data_json.get("start_date")
    end_data_str = data_json.get("end_date")

    # 2. 校验参数
    if not all([house_id, start_data_str, end_data_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        # 将日期字符串转换成　ｄａｔｅｔｉｍｅ对象
        start_data = datetime.datetime.strptime(start_data_str, "%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_data_str, "%Y-%m-%d")
        # 判断开始时间与结束时间的大小
        assert start_data < end_date, Exception("结束时间必须大于开始时间")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="结束时间必须大于开始时间")

    # 判断房屋是否存在
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据错误")

    if not house:
        return jsonify(errno=RET.NODATA, errmsg="房屋不存在")

    # 判断是否是房主去预定
    if user_id == house_id:
        return jsonify(errno=RET.ROLEERR, errmsg="房东不能预定")

    # ４．判断房屋指定时间段内是否有冲突订单
    try:
        filters = [Order.house_id == house_id, Order.begin_date < end_date, Order.end_date > start_data]
        # 取到冲突订单的数量
        order_count = Order.query.filter(*filters).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据错误")
    # 如果冲突订单的数量大于０，代表该房屋已被预定
    if order_count > 0:
        return jsonify(errno=RET.DATAERR, errmsg="房屋已被预定")
    # 5.生成订单模型
    order = Order()
    # 设置属性值
    days = (end_date - start_data).days
    order.user_id = user_id
    order.house_id = house_id
    order.begin_date = start_data
    order.end_date = end_date
    order.days = days
    order.house_price = house.price
    order.amount = days * house.price

    # 房屋订单数量加１
    house.order_count += 1

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="下单成功")


@api.route('/orders')
@login_required
def get_order():
    """查询订单"""
    # 1.获取参数
    user_id = g.user_id
    role = request.args.get('role')
    if not role:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if role not in ('custom', 'landlord'):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    orders = None
    try:
        if role == 'custom':
            orders = Order.query.filter(Order.user_id == user_id).order_by(Order.create_time.desc()).all()
        elif role == 'landlord':
            houses = House.query.filter(House.user_id == user_id).all()
            houses_id = [house.id for house in houses]
            orders = Order.query.filter(Order.house_id.in_(houses_id)).order_by(Order.create_time.desc())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询异常")
    order_dict_list = []
    for order in orders:
        order_dict_list.append(order.to_dict())
    return jsonify(errno=RET.OK, errmsg="查询成功", data={"orders": order_dict_list})


@api.route("/orders", methods=["PUT"])
@login_required
def change_order_status():
    """修改订单状态"""
    user_id = g.user_id
    json_data = request.json
    order_id = json_data.get("order_id")
    action = json_data.get("action")

    if not all([order_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_ACCEPT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not order:
        return jsonify(errno=RET.NODATA, errmsg="未查询到订单")
    if order.house.user_id != user_id:
        return jsonify(errno=RET.ROLEERR, errmsg="操作不允许")
    if action == "accept":
        order.status = "WAIT_PAYMENT"
    elif action == "reject":
        order.status = "REJECTED"
        reason = json_data.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="请填写原因")
        order.comment = reason

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")
